package com.unieagle.exam.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.unieagle.exam.R;
import com.unieagle.exam.account.AccountManager;

/**
 * 考试准备页面
 * @author QianJing
 *
 */
public class PreExamActivity extends BaseActivity{
	
	private Button mBtnStart, mBtnLook;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pre_exam_activity_layout);
		init();
	}
	
	protected void init() {
		super.init();
		mTvTitle.setText(getIntent().getStringExtra("title2"));
		mBtnStart = (Button) findViewById(R.id.exam);
		mBtnStart.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(!AccountManager.getInstance().getUserInfo().getActivation_status().equals("activation_active")) { //非激活用户
					startExam(getIntent().getIntExtra("id", -1));
				} else { //激活用户
					if(!checkIsExpired()) {
						startExam(getIntent().getIntExtra("id", -1));
					} else {
						 Toast.makeText(PreExamActivity.this, "您的帐户已过期，如有需要，请联系腾飞安培。谢谢", Toast.LENGTH_SHORT).show();
						 AccountManager.getInstance().getUserInfo().setActivation_status("activation_expired");
						 AccountManager.getInstance().updateUserInfoResult(AccountManager.getInstance().getUserInfo());
						 Intent i = new Intent(PreExamActivity.this, SubjectChooseActivity.class);
						 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
						 startActivity(i);
					}
				}
			}
		});
		mBtnLook = (Button) findViewById(R.id.look);
		mBtnLook.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				showCases(getIntent().getIntExtra("id", -1));
			}
		});
	}
	
	private boolean checkIsExpired() {
		Long current = System.currentTimeMillis();
		long expired;
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
        	expired = f.parse(AccountManager.getInstance().getUserInfo().getActivation_expired_at()).getTime();
        } catch (ParseException e) {
        	e.printStackTrace();
        	return false;
        } catch (Exception ee) {
        	return false;
        }
		return current > expired;
	}
	
	private void startExam(int id) {
		Intent i = new Intent(this, ExamActivity.class);
		i.putExtra("id", id);
		startActivity(i);
	}
	
	private void showCases(int id) {
		Intent i = new Intent(this, CasesActivity.class);
		i.putExtra("id", id);
		i.putExtra("title", getIntent().getStringExtra("title2"));
		startActivity(i);
	}
	
}
